<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content" :style="{ height: navBarHeight + 'px' }">
				<view class="nav-left" @click="goBack">
					<u-icon name="arrow-left" size="20" color="#333"></u-icon>
				</view>
				<view class="nav-title">
					<text class="title-text">{{ pageTitle }}</text>
				</view>
				<view class="nav-right">
					<!-- 可以添加分享等功能 -->
				</view>
			</view>
		</view>

		<!-- 专区头部图片 -->
		<view class="zone-header" v-if="zoneInfo.headerImage">
			<image :src="defaults.defaults.baseUrl + zoneInfo.headerImage" class="header-image" mode="aspectFill"></image>
		</view>

		<!-- 专区介绍 -->
		<view class="zone-intro" v-if="zoneInfo.introduction">
			<text class="intro-text">{{ zoneInfo.introduction }}</text>
		</view>

		<!-- 分类导航 -->
		<view class="category-nav" v-if="categoryList.length > 0">
			<scroll-view class="nav-scroll" scroll-x>
				<view class="nav-item" 
					v-for="(item, index) in categoryList" 
					:key="index"
					:class="{ active: currentCategoryIndex === index }"
					@click="switchCategory(index)">
					<text class="nav-text">{{ item.name }}</text>
					<view class="nav-bar" v-if="currentCategoryIndex === index"></view>
				</view>
			</scroll-view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-container">
			<swiper class="goods-swiper" :current="currentCategoryIndex" @change="swiperChange">
				<swiper-item v-for="(category, categoryIndex) in categoryList" :key="categoryIndex">
					<scroll-view class="goods-scroll" scroll-y @scrolltolower="loadMoreGoods">
						<view class="goods-grid">
							<view class="goods-item" 
								v-for="(item, index) in category.goodsList" 
								:key="index"
								@click="goProductDetail(item)">
								<view class="goods-image-wrapper">
									<image :src="defaults.defaults.baseUrl + item.image" class="goods-image" mode="aspectFill"></image>
									<view class="goods-tag" v-if="item.tag">{{ item.tag }}</view>
								</view>
								<view class="goods-info">
									<text class="goods-title">{{ item.title }}</text>
									<view class="goods-spec" v-if="item.goodsSpec">
										<text class="spec-text">{{ item.goodsSpec }}</text>
									</view>
									<view class="goods-price">
										<text class="current-price">￥{{ item.price }}</text>
										<text class="original-price" v-if="item.originalPrice && item.originalPrice !== item.price">￥{{ item.originalPrice }}</text>
									</view>
									<view class="goods-profit" v-if="item.maxProfit && item.maxProfit !== '0.00'">
										<text class="profit-label">分润</text>
										<text class="profit-amount">￥{{ item.maxProfit }}</text>
									</view>
								</view>
							</view>
						</view>
						
						<!-- 加载更多 -->
						<view class="load-more" v-if="category.showLoadMore">
							<text class="load-text">{{ category.loadMoreText }}</text>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script>
import api from '@/api/index.js'
import { inject } from 'vue'

export default {
	data() {
		return {
			// 小程序适配相关
			statusBarHeight: 0,
			navBarHeight: 44,
			// 页面数据
			pageTitle: '专区',
			zoneId: '',
			zoneInfo: {
				headerImage: '',
				introduction: ''
			},
			categoryList: [],
			currentCategoryIndex: 0,
			loading: false,
			defaults: inject('$defaults')
		}
	},
	onLoad(options) {
		this.initMiniProgramAdapt()
		
		// 获取传入的参数
		if (options.id) {
			this.zoneId = options.id
		}
		if (options.title) {
			this.pageTitle = decodeURIComponent(options.title)
		}
		
		this.loadZoneData()
	},
	
	methods: {
		// 小程序适配初始化
		initMiniProgramAdapt() {
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
			
			// #ifdef MP
			try {
				const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
				this.navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - this.statusBarHeight) * 2
			} catch (e) {
				this.navBarHeight = 44
			}
			// #endif
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载专区数据
		async loadZoneData() {
			this.loading = true
			try {
				// 调用专区主题接口
				const themeResult = await api.systemApi.getThemeInfo({
					rel_id: this.zoneId
				})
				
				if (themeResult.r === 0) {
					// 设置专区信息
					this.zoneInfo = {
						headerImage: themeResult.data.file_path,
						introduction: themeResult.data.intro
					}
					
					// 设置页面标题
					if (themeResult.data.t_name) {
						this.pageTitle = themeResult.data.t_name
					}
					
					// 设置分类列表
					if (themeResult.data.group && themeResult.data.group.length > 0) {
						this.categoryList = themeResult.data.group.map(group => ({
							id: group.g_id,
							name: group.g_name,
							goodsList: [],
							currentPage: 1,
							hasMore: true,
							showLoadMore: false,
							loadMoreText: '上拉加载更多'
						}))
						
						// 加载第一个分类的商品
						await this.loadCategoryGoods(0)
					} else {
						// 如果没有分组，创建默认的"全部"分类
						this.categoryList = [{
							id: 0,
							name: '全部',
							goodsList: [],
							currentPage: 1,
							hasMore: true,
							showLoadMore: false,
							loadMoreText: '上拉加载更多'
						}]
						
						// 加载商品
						await this.loadCategoryGoods(0)
					}
				} else {
					console.error('获取专区数据失败:', themeResult.msg)
					// 加载模拟数据
					this.loadMockData()
				}
			} catch (error) {
				console.error('加载专区数据失败:', error)
				// 加载模拟数据
				this.loadMockData()
			} finally {
				this.loading = false
			}
		},
		
		// 加载模拟数据
		loadMockData() {
			this.zoneInfo = {
				headerImage: '/static/zone-header.jpg',
				introduction: '精选优质商品，为您带来更好的购物体验'
			}
			
			this.categoryList = [
				{
					id: 1,
					name: '全部',
					goodsList: this.generateMockGoods(20),
					currentPage: 1,
					hasMore: true,
					showLoadMore: false,
					loadMoreText: '上拉加载更多'
				},
				{
					id: 2,
					name: '热销',
					goodsList: this.generateMockGoods(15),
					currentPage: 1,
					hasMore: true,
					showLoadMore: false,
					loadMoreText: '上拉加载更多'
				},
				{
					id: 3,
					name: '新品',
					goodsList: this.generateMockGoods(12),
					currentPage: 1,
					hasMore: true,
					showLoadMore: false,
					loadMoreText: '上拉加载更多'
				}
			]
		},
		
		// 生成模拟商品数据
		generateMockGoods(count) {
			const goods = []
			for (let i = 0; i < count; i++) {
				goods.push({
					id: i + 1,
					title: `精选商品 ${i + 1}`,
					image: '/static/goods-placeholder.jpg',
					price: (Math.random() * 100 + 10).toFixed(2),
					originalPrice: (Math.random() * 150 + 50).toFixed(2),
					maxProfit: (Math.random() * 20).toFixed(2),
					tag: i % 3 === 0 ? '热销' : (i % 3 === 1 ? '新品' : '')
				})
			}
			return goods
		},
		
		// 加载分类商品
		async loadCategoryGoods(categoryIndex) {
			const category = this.categoryList[categoryIndex]
			if (!category) return
			
			try {
				const result = await api.systemApi.getThemeGoodsList({
					page: category.currentPage,
					rel_id: this.zoneId,
					group_id: category.id,
					size: 10
				})
				
				if (result.r === 0 && result.data && result.data.list) {
					const goodsList = result.data.list.map(item => ({
						id: item.goods_id,
						title: item.goods_name,
						image: item.file_path,
						price: item.sale_price,
						handPrice: item.hand_price,
						maxProfit: item.rebate_price,
						goodsSpec: item.goods_spec,
						huafan: item.huafan,
						activityLabel: item.activity_label
					}))
					
					if (category.currentPage === 1) {
						// 第一页，直接赋值
						category.goodsList = goodsList
					} else {
						// 后续页，追加数据
						category.goodsList.push(...goodsList)
					}
					
					// 判断是否还有更多数据
					category.hasMore = goodsList.length >= 10
				} else {
					category.hasMore = false
				}
			} catch (error) {
				console.error('加载分类商品失败:', error)
				category.hasMore = false
			}
		},
		
		// 切换分类
		async switchCategory(index) {
			this.currentCategoryIndex = index
			
			// 如果该分类还没有加载商品，则加载
			const category = this.categoryList[index]
			if (category && category.goodsList.length === 0) {
				await this.loadCategoryGoods(index)
			}
		},
		
		// swiper切换事件
		async swiperChange(e) {
			const newIndex = e.detail.current
			this.currentCategoryIndex = newIndex
			
			// 如果该分类还没有加载商品，则加载
			const category = this.categoryList[newIndex]
			if (category && category.goodsList.length === 0) {
				await this.loadCategoryGoods(newIndex)
			}
		},
		
		// 加载更多商品
		async loadMoreGoods() {
			const currentCategory = this.categoryList[this.currentCategoryIndex]
			if (!currentCategory || currentCategory.showLoadMore || !currentCategory.hasMore) {
				return
			}
			
			currentCategory.showLoadMore = true
			currentCategory.loadMoreText = '加载中...'
			
			try {
				// 增加页码
				currentCategory.currentPage++
				
				// 加载下一页数据
				await this.loadCategoryGoods(this.currentCategoryIndex)
				
				if (!currentCategory.hasMore) {
					currentCategory.loadMoreText = '没有更多了'
				} else {
					currentCategory.loadMoreText = '上拉加载更多'
				}
			} catch (error) {
				console.error('加载更多失败:', error)
				currentCategory.loadMoreText = '加载失败，请重试'
				// 回退页码
				currentCategory.currentPage--
			} finally {
				currentCategory.showLoadMore = false
			}
		},
		
		// 跳转商品详情
		goProductDetail(item) {
			uni.navigateTo({
				url: `/pages/goods/detail?id=${item.id}&title=${encodeURIComponent(item.title || '')}`
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	background: #f5f5f5;
	min-height: 100vh;
}

/* 自定义导航栏 */
.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	background: #fff;
	z-index: 1000;
	border-bottom: 1px solid #eee;
}

.navbar-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 15px;
}

.nav-left, .nav-right {
	width: 40px;
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-title {
	flex: 1;
	text-align: center;
}

.title-text {
	font-size: 18px;
	font-weight: 600;
	color: #333;
}

/* 专区头部 */
.zone-header {
	width: 100%;
	height: 200px;
	margin-top: 88px;
	overflow: hidden;
}

.header-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

/* 专区介绍 */
.zone-intro {
	padding: 15px;
	background: #fff;
	margin-bottom: 10px;
}

.intro-text {
	font-size: 14px;
	color: #666;
	line-height: 1.6;
}

/* 分类导航 */
.category-nav {
	background: #fff;
	border-bottom: 1px solid #eee;
	margin-bottom: 10px;
}

.nav-scroll {
	white-space: nowrap;
	padding: 0 15px;
}

.nav-item {
	display: inline-block;
	position: relative;
	padding: 15px 20px;
	margin-right: 10px;
}

.nav-text {
	font-size: 16px;
	color: #666;
	transition: color 0.3s;
}

.nav-item.active .nav-text {
	color: #ff6b6b;
	font-weight: 600;
}

.nav-bar {
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 20px;
	height: 3px;
	background: #ff6b6b;
	border-radius: 2px;
}

/* 商品容器 */
.goods-container {
	flex: 1;
	height: calc(100vh - 300px);
}

.goods-swiper {
	height: 100%;
}

.goods-scroll {
	height: 100%;
}

.goods-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 10px;
	padding: 15px;
}

.goods-item {
	background: #fff;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	transition: transform 0.2s;
}

.goods-item:active {
	transform: scale(0.98);
}

.goods-image-wrapper {
	position: relative;
	width: 100%;
	height: 160px;
	overflow: hidden;
}

.goods-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.goods-tag {
	position: absolute;
	top: 8px;
	left: 8px;
	background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
	color: #fff;
	font-size: 12px;
	padding: 4px 8px;
	border-radius: 10px;
	font-weight: 500;
}

.goods-info {
	padding: 12px;
}

.goods-title {
	font-size: 14px;
	color: #333;
	line-height: 1.4;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	text-overflow: ellipsis;
	margin-bottom: 8px;
	height: 40px;
}

.goods-spec {
	margin-bottom: 8px;
}

.spec-text {
	font-size: 12px;
	color: #999;
}

.goods-price {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
}

.current-price {
	font-size: 16px;
	color: #ff6b6b;
	font-weight: 600;
	margin-right: 8px;
}

.original-price {
	font-size: 12px;
	color: #999;
	text-decoration: line-through;
}

.goods-profit {
	display: flex;
	align-items: center;
}

.profit-label {
	font-size: 12px;
	color: #fff;
	background: #ff6b6b;
	padding: 2px 6px;
	border-radius: 8px;
	margin-right: 6px;
}

.profit-amount {
	font-size: 12px;
	color: #ff6b6b;
	font-weight: 600;
}

/* 加载更多 */
.load-more {
	padding: 20px;
	text-align: center;
}

.load-text {
	font-size: 14px;
	color: #999;
}
</style>